//
//  LoginViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/13.
//

import UIKit
import AuthenticationServices

var loginNaviController: XGLNavigationController{
    let vc = XGLNavigationController(rootViewController: LoginViewController())
    vc.modalPresentationStyle = .fullScreen
    return vc
}

class LoginViewController: UIViewController,CustomNavgationBar{
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var loginView: LoginView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.createCustomBackgroundView()
        self.loginView = LoginView().then({ make in
            make.delegate = self
        })
        self.view.addSubview(self.loginView)
        self.loginView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        DispatchQueue.main.async {
            self.navigationController?.isNavigationBarHidden = true
        }
    }
}



extension LoginViewController: LoginDelegate{
    func loginWithEmail() {
        let alertView = LoginAlertView()
        alertView.showAlertView {
            let vc = LoginWithEmailViewController()
            self.navigationController?.pushViewController(vc)
        }
        self.view.addSubview(alertView)
        alertView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func loginWithApple() {
        let alertView = LoginAlertView()
        alertView.showAlertView {
            let appleIDProvider = ASAuthorizationAppleIDProvider()
            let request = appleIDProvider.createRequest()
            request.requestedScopes = [.fullName, .email]
            
            let authorizationController = ASAuthorizationController(authorizationRequests: [request])
            authorizationController.delegate = self
            authorizationController.presentationContextProvider = self
            authorizationController.performRequests()
        }
        self.view.addSubview(alertView)
        alertView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func aboutTeam() {
        let vc = XGL_CustomWebViewController()
        vc.navTitle = "Terms of Use"
        vc.url = Terms
        self.navigationController?.pushViewController(vc)
    }
    
    func privacyPolicy() {
        let vc = XGL_CustomWebViewController()
        vc.navTitle = "Privacy Policy"
        vc.url = PrivacyPolicy
        self.navigationController?.pushViewController(vc)
    }
    
    
}

extension LoginViewController{
    private func loginWithAppleRequest(thirdId: String,appleCode: String,nickname: String?){
        self.hudView.hudView.startAnimation()
        self.hudView.hudView.backgroundColor = .clear
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<LoginData>,XGL_CustomRequestError>().request(LoginRequestAPI(requestAPI: .LoginWithApple(thirdId: thirdId, appleCode: appleCode, nickname: nickname))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let result = response.resultData {
                    let infor = XGL_userDataCacheManager.shared.token
                    infor.token = result.token
                    LoginInfor.share.infor = result
                    UserDefaults.standard.set(result.userId, forKey: XGL_AppInforCacheKey.share.userDefaultsAccountKey)
                    XGL_userDataCacheManager.shared.saveInfor(inforData: infor)
                    if result.profileStatus == 0 {
                        let vc = EditProfileHeaderViewController()
                        vc.nickName = nickname
                        self.navigationController?.pushViewController(vc)
                    }else{
//                        self.dismiss(animated: true)
                        if let window = UIApplication.shared.currentWindow {
                            window.rootViewController = MainViewController
                        }
                    }
                }
                break
            default:
                break
            }
        }
    }
}

extension LoginViewController: ASAuthorizationControllerDelegate {
    /// - Tag: did_complete_authorization
    func authorizationController(controller: ASAuthorizationController,
      didCompleteWithAuthorization authorization: ASAuthorization) {
        /// login success
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential{
            var name: String?
            if let fullName = appleIDCredential.fullName,let familyName = fullName.familyName,let givenName = fullName.givenName {
                name = "\(givenName)\(familyName)"
            }
            if let codeData = appleIDCredential.authorizationCode,let code = codeData.string(encoding: .utf8){
                self.loginWithAppleRequest(thirdId: appleIDCredential.user, appleCode: code, nickname: name)
            }
        }
        
    }

    /// - Tag: did_complete_error
    func authorizationController(controller: ASAuthorizationController,
      didCompleteWithError error: Error) {
        // Handle error.
        debugPrint("login failed: \(error)")
        
    }
}

extension LoginViewController: ASAuthorizationControllerPresentationContextProviding {
    /// - Tag: provide_presentation_anchor
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.view.window!
    }
}
